﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Hids.Enums;

namespace Hids.Classes
{
    /// <summary>
    /// This class provides methods for helping write to the log files
    /// </summary>
    public class Logs
    {
        #region Private Properties

        /// <summary>
        /// Defines the location of the HIDS log folder
        /// </summary>
        private static string LogFolder = "./logs/";

        #endregion

        #region Static Method

        /// <summary>
        /// Writes the specified message to the log file.  The message has the date/time prepended to it
        /// </summary>
        /// <param name="message">The message to write to the log file</param>
        public static void WriteMessageToLog(string message)
        {
            lock (LogFolder)//ensure only one thread is attempting to write to the log at a time
            {
                //Create the log directory if it is needed
                if (!Directory.Exists(LogFolder))
                    Directory.CreateDirectory(LogFolder);

                //Create a unqiue log file name based on the day
                string currentLogFilePath = "Davjd Log-";
                if (DateTime.Now.Month <= 9)
                    currentLogFilePath += "0";
                currentLogFilePath += DateTime.Now.Month.ToString();
                if (DateTime.Now.Day <= 9)
                    currentLogFilePath += "0";
                currentLogFilePath += DateTime.Now.Day.ToString() + DateTime.Now.Year.ToString() + ".txt";

                //Open the file (and create it if needed)
                List<string> files = new List<string>(Directory.GetFiles(LogFolder));
                StreamWriter logFileWriter = null;

                if (!files.Contains(LogFolder + currentLogFilePath))
                    logFileWriter = File.CreateText(LogFolder + currentLogFilePath);
                else
                    logFileWriter = new StreamWriter(LogFolder + currentLogFilePath, true);

                //Write to the file and close it
                logFileWriter.WriteLine(DateTime.Now.ToString() + ":  " + message);
                logFileWriter.Close();
            }
        }

        #endregion
    }
}
